#!/usr/bin/env bash

# DESCRIPTION
#     This script is called as-is and included with every patch update for historical
#     and compatibility reasons. As of version 3.2.0 this patch is optional. It reduces
#     the CPU usage on kernels with timer frequencies lower than 1000 Hz.
#
# EXIT STATUS
#     0      : The patch was applied successfully or is not needed for this game version.
#     other  : Patch failure. See stdout or stderr output for details.


# Templates for the next patch testing phase
#echo "          This is an OPTIONAL patch to reduce CPU usage by disabling mhypbase.dll."
#echo "[WARNING]       !! UNTESTED PATCH. CHECK FOR BANS USING A TRASH ACCOUNT !!"
#echo ""
#echo "If you would like to test this patch, modify this script and remove the line below this one."
#exit 0

# MacOS and *BSD do not have md5sum: use md5 instead
if [[ $(uname) == "Darwin" || $(uname) == *"BSD" ]]; then
	md5sum() {
		md5 -q $@
	}
fi

DIR=$(dirname "${BASH_SOURCE[0]}")
DATADIR=$(find -maxdepth 1 -type d -name "*_Data")
FILE="$DATADIR/Plugins/xlua.dll"
sum=($(md5sum $FILE))
reltype=""

# original hashes
if [ "${sum}" == "dbc851960002f3b9b05ddab0b228ba8c" ]; then
	reltype="os"
	echo "--- Applying for: International (OS) version"
fi
if [ "${sum}" == "01f73cf535c4ecf26120fc4f750e4181" ]; then
	reltype="cn"
	echo "--- Applying for: Chinese (CN) version"
fi
if [ -z "$reltype" ]; then
	# The patch might corrupt invalid/outdated files if this check is skippd.
	echo "[ERROR] Wrong file version or the patch is already applied"
	echo " -> md5sum: ${sum}" && exit 1
fi


# =========== DO NOT REMOVE START ===========
if [[ -e "$DIR/$FILE" ]]; then
	# There is a good reason for this check. Do not pollute the game directory.
	echo "[ERROR] Invalid patch download directory. Please move all"
	echo "        patch files outside the game directory prior executing."
	echo " -> See README.md for proper installation instructions" && exit 1
fi
# ===========  DO NOT REMOVE END  ===========


if ! command -v xdelta3 &>/dev/null; then
	echo "[ERROR] xdelta3 application is required"
	exit 1
fi

#echo "[INFO]    Patch to fix a login and runtime crash"

# ===========================================================
echo ""
echo "[WARNING] Hereby you are violating the game's Terms of Service!"
echo "          Do you accept the risk and possible consequences?"
echo "          Use Ctrl+C to abort this script if you are not sure."
read -p "Accept? [y/N] " choice

if [[ ! "$choice" == [JjSsYy]* ]]; then
	exit 1
fi

echo
echo "--- Patching xLua"
xdelta_fail() {
	mv -vf "$FILE.bak" "$FILE"
	exit 1
}

mv -f "$FILE" "$FILE.bak"
# Perform patch or restore .bak on failure
xdelta3 -d -s "$FILE.bak" "$DIR/patch_files/xlua_patch_${reltype}.vcdiff" "$FILE" || xdelta_fail

# Disable by renaming
echo "--- Disabling mhypbase"
mv -f "mhypbase.dll" "mhypbase.dll.bak"

# Done!
echo "==> Patch applied! Enjoy the game."
exit 0
